package com.example.springboot3.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.time.Duration;
import java.util.Date;

/**
 * @author 张琪
 * @date 2024-02-26 14:43
 */
@Slf4j
public class JwtUtil {

    /**
     * 密钥
     */
    private static final String SECRET_KEY = "fakeKey";

    /**
     * 过期时间
     */
    private static final Duration EXPIRATION = Duration.ofDays(2);

    public static String generateToken(String username) {
        // 过期时间
        Date expiryDate = new Date(System.currentTimeMillis() + EXPIRATION.toMillis());
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    public static Claims parse(String token) {

        if (StringUtils.isBlank(token)) {
            return null;
        }

        Claims claims = null;
        // 解析失败了会抛出异常，所以我们要捕捉一下。token过期、token非法都会导致解析失败
        try {
            claims = Jwts.parser()
                    // 设置秘钥
                    .setSigningKey(SECRET_KEY)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (JwtException e) {
            log.error("解析token失败", e);
        }
        return claims;
    }
}
